import { BaseCardExtractor } from './base-card-extractor.js';
import { selectors } from '../config.js';

export class ListCardExtractor extends BaseCardExtractor {
  constructor() {
    super({
      card: selectors.listCard,
      item: selectors.listItem
    });
  }

  // 获取列表标题
  getTitleForList(listNode) {
    let current = listNode;
  
    for (let i = 0; i < 5 && current; i++) {
      const parent = current.parentElement;
      if (!parent) break;
  
      const divs = Array.from(parent.children).filter(el => el.tagName === 'DIV');
      const index = divs.indexOf(current);
  
      // 当前是兄弟div结构中的第二个
      if (divs.length === 2 && index === 1) {
        const headerDiv = divs[0];
  
        // 从 headerDiv 内取第一个非空文本作为标题
        const text = headerDiv.textContent.trim();
        if (text) return text;
      }
  
      current = parent;
    }
  
    return null;
  }
  

  // 提取销售额
  extractSalesAmountSafely(card) {
    const blocks = Array.from(card.querySelectorAll("div"));
    for (let i = 0; i < blocks.length - 1; i++) {
      const maybeValue = blocks[i].innerText?.trim();
      const maybeLabel = blocks[i + 1].innerText?.trim();

      if (/^¥[\d,.]+$/.test(maybeValue)) {
        const excluded = ["原价", "售价", "现价", "价格", "套餐"];
        const isExcluded = excluded.some(w => maybeLabel.includes(w));
        if (!isExcluded) {
          return parseFloat(maybeValue.replace(/[¥,]/g, ""));
        }
      }
    }

    const allDivs = card.querySelectorAll("div");
    const values = [];

    for (let i = 0; i < allDivs.length - 1; i++) {
      const valueText = allDivs[i].innerText?.trim();
      const labelText = allDivs[i + 1].innerText?.trim();
      if (/^¥[\d,.]+$/.test(valueText)) {
        values.push({
          value: parseFloat(valueText.replace(/[¥,]/g, "")),
          label: labelText
        });
      }
    }

    if (values.length === 1) return values[0].value;
    if (values.length > 0) {
      return values.sort((a, b) => b.value - a.value)[0].value;
    }

    return null;
  }

  // 提取单个商品数据
  extractProductData(card) {
    const productNameEl = card.querySelector(selectors.listItemName);
    const productName = productNameEl?.innerText.trim() || "";

    const priceEl = card.querySelector(selectors.listItemPrice);
    const productPriceText = priceEl?.childNodes?.[0]?.textContent?.trim() || "";
    const productPrice = parseFloat(productPriceText.replace("¥", "")) || null;

    const originalPriceEl = priceEl?.querySelector(selectors.listItemOriginalPrice);
    const productOriginalPrice = originalPriceEl
      ? parseFloat(originalPriceEl.innerText.replace("¥", ""))
      : productPrice;

    const imageEl = card.querySelector(selectors.listItemImage);
    const productImage = imageEl?.src || "";

    const salesAmount = this.extractSalesAmountSafely(card);

    const packageTypeEl = card.querySelector("span[style*='border-radius']");
    const packageType = packageTypeEl?.innerText.trim() || "";

    if (productName && productPrice !== null) {
      return {
        productName,
        productPrice,
        productOriginalPrice,
        productImage,
        salesAmount,
        packageType
      };
    }
    return null;
  }

  // 去重函数
  removeDuplicates(products) {
    const uniqueProducts = new Map();

    products.forEach(product => {
      const key = `${product.productName}_${product.productPrice}`;
      if (!uniqueProducts.has(key)) {
        uniqueProducts.set(key, product);
      } else {
        const existingProduct = uniqueProducts.get(key);
        if (product.salesAmount !== null && existingProduct.salesAmount === null) {
          uniqueProducts.set(key, product);
        }
      }
    });

    return Array.from(uniqueProducts.values());
  }

  // 重写提取方法
  extract(cardElement) {
    const itemSelector = 'div.byted-row.byted-row-type-flex';
    const allItems = Array.from(document.querySelectorAll(itemSelector)).filter(el => el.offsetParent !== null);

    function findShallowCommonAncestor(el1, el2, maxDepth = 4) {
      const getAncestors = (el, depth) => {
        const result = [];
        let current = el;
        for (let i = 0; i <= depth; i++) {
          if (current) result.push(current);
          current = current?.parentElement;
        }
        return result;
      };
      const ancestors1 = getAncestors(el1, maxDepth);
      const ancestors2 = new Set(getAncestors(el2, maxDepth));
      for (const a of ancestors1) {
        if (ancestors2.has(a)) return a;
      }
      return null;
    }

    const groups = [];
    const visited = new Set();

    for (let i = 0; i < allItems.length; i++) {
      if (visited.has(allItems[i])) continue;

      const groupItems = [allItems[i]];
      visited.add(allItems[i]);
      let lastCommonAncestor = allItems[i];

      for (let j = i + 1; j < allItems.length; j++) {
        const a = groupItems[groupItems.length - 1];
        const b = allItems[j];
        const common = findShallowCommonAncestor(a, b, 4);
        if (common) {
          groupItems.push(b);
          visited.add(b);
          lastCommonAncestor = common;
        } else {
          break;
        }
      }

      if (groupItems.length >= 2) {
        groups.push({ items: groupItems, ancestor: lastCommonAncestor });
      }
    }

    const groupObj = groups.find(g => g.items.includes(cardElement));
    if (!groupObj) return null;

    const { items: group, ancestor } = groupObj;
    if (group[0] !== cardElement) return null;

    const groupIndex = groups.indexOf(groupObj);
    const groupTitle = this.getTitleForList(ancestor) || `第${groupIndex + 1}组`;

    const parent = group[0].parentElement;
    parent.style.position = 'relative';

    const label = document.createElement('div');
    label.textContent = groupTitle;
    label.className = 'auto-group-label';
    label.style.cssText = `
      position: absolute;
      top: -25px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 16px;
      font-weight: bold;
      color: red;
      background: #f5f5f5;
      border: 2px solid red;
      border-radius: 0;
      padding: 2px 6px;
      z-index: 9999;
      pointer-events: none;
    `;
    parent.appendChild(label);

    group.forEach((el, i) => {
      el.style.backgroundColor = `hsla(${(groupIndex * 40) % 360}, 70%, 80%, 0.3)`;
      el.style.border = '1px solid #999';
      el.style.borderRadius = '6px';
    });

    const products = [];
    group.forEach(card => {
      const productData = this.extractProductData(card);
      if (productData) {
        products.push(productData);
      }
    });

    if (products.length > 0) {
      const uniqueProducts = this.removeDuplicates(products);
      return {
        label: groupTitle,
        value: uniqueProducts
      };
    }

    return null;
  }
}
